﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace RFPL
{
    public partial class CountrySelect : Form
    {
        public int countryId = 0;

        public CountrySelect()
        {
            InitializeComponent();
        }
        
        private void CountrySelect_Load(object sender, EventArgs e)
        {
            UpdateCountryList();
        }

        private void UpdateCountryList() {

            dgvCountries.Rows.Clear();

            SqlDataReader dataReader = Global.getDataReader("[getAllCountries]");
            while (dataReader.Read())
            {
                dgvCountries.Rows.Add(dataReader["id"], dataReader["flag"], dataReader["name"]);
            }
            dataReader.Close();
            Global.closeConnection();

        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            countryId = Convert.ToInt32(dgvCountries.SelectedRows[0].Cells["id"].Value);
            this.Close();                     
        }
        
        private void add_Click(object sender, EventArgs e)
        {
            CountryInfo nc = new CountryInfo(0);
            nc.ShowDialog();

            UpdateCountryList();
        }

        private void del_Click(object sender, EventArgs e)
        {
            
            int delID = Convert.ToInt32(dgvCountries.SelectedRows[0].Cells["id"].Value);

            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = Global.connectionString;
            SqlCommand myCommand = conn.CreateCommand();
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.CommandText = "[delCountry]";
            myCommand.Parameters.Add("@id", SqlDbType.Int).Value = delID;
            
            conn.Open();
            myCommand.ExecuteScalar();
            conn.Close();

            UpdateCountryList();
           
        }

        private void dgvCountries_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvCountries.SelectedRows.Count > 0)
            {
                del.Enabled = true;
                edit.Enabled = true;
                saveButton.Enabled = true;
            }
            else {
                del.Enabled = false;
                edit.Enabled = false;
                saveButton.Enabled = false;
            }
        }

        private void edit_Click(object sender, EventArgs e)
        {
            int editID = Convert.ToInt32(dgvCountries.SelectedRows[0].Cells["id"].Value);

            CountryInfo ci = new CountryInfo(editID);
            ci.ShowDialog();
                        
            UpdateCountryList();
        }
    }
}
